<?php

class HTech_Login 
{
    private $_authAdapter;
    private $_pwdField;
    private $_cl;
    private $_db;
    private $_auth;
    
    public function __construct($cl,$db,$usr,$pwd,$tbl,$usrField,$pwdField,$credTreatment) 
    {
        $this->_cl = $cl;
        $this->_db = $db; 
        $this->_pwdField = $pwdField;
        $this->_auth = Zend_Auth::getInstance(); 
        $conf = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', $cl . '_' . $db);
        date_default_timezone_set($conf->timezone);
        $dbOptions = Zend_Controller_Front::getInstance()
            ->getParam('bootstrap')->getOption('db');
        $db = Zend_Db::factory($dbOptions['adapter'], $conf->db->toArray());
        Zend_Registry::set('db', $db);
        Zend_Db_Table_Abstract::setDefaultAdapter($db);
        $this->_authAdapter = new Zend_Auth_Adapter_DbTable($db, $tbl, $usrField, $pwdField, $credTreatment);
        $this->_authAdapter->setIdentity($usr)->setCredential($pwd);
    }
    
    public function authenticate()
    {
        return $this->_auth->authenticate($this->_authAdapter);
    }
    
    public function saveProfile()
    {
        $data = $this->_authAdapter->getResultRowObject(null,$this->_pwdField);
        $resource = new HTech_Model_Resource(); 
        $data->resources = $resource->getResources($data->RoleId);  
        $scope = new HTech_Model_Scope($data->UserId); 
        $data->scope = $scope->getScopes();               
        $data->emmsClient = $this->_cl;
        $data->emmsDb = $this->_db;
        $data->locale = Zend_Registry::get('Zend_Locale');;
        $data->loginTime = new Zend_Date();
        $this->_auth->getStorage()->write($data);
    }
    
    public function getProfile($returnColumns = null,$omitColumns = null)
    { 
        return $this->_authAdapter->getResultRowObject($returnColumns,$omitColumns);
    }
}
